<template>
  <div id="app">
    <el-container v-loading="isUploading">
      <!-- 顶栏 -->
      <el-header>
        <h1>Speech</h1>
      </el-header>


      <el-main>
        <div
            style="
            display: flex;
            justify-content: space-around;
            align-items: center;
            margin-bottom: 20px;
          "
        >
          <!-- <el-button
            type="primary"
            @click="chooseAudio"
            readonly
            style="flex-grow: 1; margin-left: 20px"
            >选择</el-button
          > -->
          <el-button
              type="warning"
              @click="recognize"
              readonly
              style="flex-grow: 1; margin-left: 20px"
              icon="el-icon-search"
          >识别
          </el-button
          >
          <el-input
              v-model="info"
              placeholder="信息显示"
              readonly
              style="flex-grow: 1; margin-left: 30px"
          ></el-input>
        </div>
        <el-row :gutter="20">
          <!-- user列表 -->
          <el-col :span="15">
            <el-card>
              <div
                  style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  position: relative;
                "
              >
                <h2 style="flex-grow: 0; text-align: center; margin: 0">
                  用户列表
                </h2>
                <div>
                  <!--                  <el-button type="danger" @click="userAllClear">清空数据库</el-button>-->
                  <el-button type="info" @click="getUser" icon="el-icon-refresh">刷新</el-button>
                  <el-button type="primary" @click="addUser" icon="el-icon-plus">新增</el-button>
                </div>
              </div>
              <el-table :data="userList" style="width: 100%" v-loading="isUsersLoading">
                <el-table-column prop="id" label="序号"></el-table-column>
                <el-table-column
                    prop="username"
                    label="用户名"
                ></el-table-column>
                <el-table-column
                    prop="permission_level"
                    label="权限级别"
                ></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                        @click="editUser(scope.$index, scope.row)"
                        type="success"
                    >修改
                    </el-button
                    >
                    <el-button
                        @click="confirmDeleteUser(scope.row)"
                        type="danger"
                    >删除
                    </el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                  @size-change="handleSizeChangeUser"
                  @current-change="handleCurrentChangeUser"
                  :current-page="currentPageUser"
                  :page-sizes="[5, 10, 20, 50]"
                  :page-size="pageSizeUser"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalUsers">
              </el-pagination>
            </el-card>
          </el-col>

          <!-- action列表 -->
          <el-col :span="9">
            <el-card>
              <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                "
              >
                <h2>指令列表</h2>
                <div>
                  <el-button type="info" @click="getCommand" icon="el-icon-refresh">刷新</el-button>
                  <el-button type="primary" @click="addCommand" icon="el-icon-plus">新增</el-button>
                </div>
              </div>
              <el-table :data="commandList" style="width: 100%" v-loading="isCommandLoading">
                <el-table-column prop="command" label="指令"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                        @click="confirmDeleteCommand(scope.row)"
                        type="danger"
                    >删除
                    </el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                  @size-change="handleSizeChangeCommand"
                  @current-change="handleCurrentChangeCommand"
                  :current-page="currentPageCommand"
                  :page-sizes="[5, 10, 20, 50]"
                  :page-size="pageSizeCommand"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCommands">
              </el-pagination>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 用户表单对话框 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="userDialogFormVisible"
        width="40%"
    >
      <el-form :model="userFormData" ref="form" v-loading="isUploading" element-loading-text="正在提交">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="userFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="等级" :label-width="formLabelWidth">
          <el-input
              v-model="userFormData.permission_level"
              type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="音频文件" :label-width="formLabelWidth">
          <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              :multiple="true"
              :before-upload="handleBeforeUpload"
              :on-change="handleFileChange"
              :file-list="fileList"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">只能上传wav文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <ul>
            <li v-for="(file, index) in fileList" :key="index">
              <i class="el-icon-document"></i> {{ file.name }}
            </li>
          </ul>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 音频识别对话框 -->
    <el-dialog
        title="音频识别"
        :visible.sync="audioDialogFormVisible"
        width="40%"
    >
      <el-form :model="userFormData" ref="form" v-loading="isRecognizing" element-loading-text="正在识别">
        <el-form-item label="音频文件" :label-width="formLabelWidth">
          <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              :multiple="true"
              :before-upload="handleBeforeUpload"
              :on-change="handleFileChange"
              :file-list="fileList"
              :limit="1"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">只能上传wav文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <ul>
            <li v-for="(file, index) in fileList" :key="index">
              <i class="el-icon-document"></i> {{ file.name }}
            </li>
          </ul>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="audioDialogFormVisible = false" :disabled="isRecognizing">取消</el-button>
        <el-button type="primary" @click="recognizeAudio" :disabled="isRecognizing">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      httpTarget: "http://127.0.0.1:5000", // 定义全局 HTTP 目标
      info: "",
      userList: [], // 初始化为空
      commandList: [], // 初始化为空
      currentPageUser: 1, // 用户表格的当前页
      currentPageCommand: 1, // 指令表格的当前页
      pageSizeUser: 5, // 用户表格的每页显示数量
      pageSizeCommand: 5, // 指令表格的每页显示数量
      totalUsers: 0, // 用户总数
      totalCommands: 0, // 指令总数
      userDialogFormVisible: false,
      audioDialogFormVisible: false,
      formLabelWidth: "100px",
      userFormData: {
        username: "",
        permission_level: 1,
        user_id: 0,
      },
      dialogTitle: "新增用户",
      isEditing: false,
      fileList: [],
      isRecognizing: false, // 增加识别状态
      isUploading: false,
      isCommandLoading: false,
      isUsersLoading: false,
    };
  },
  mounted() {
    // 页面加载时请求指令列表
    this.getCommand();
    this.getUser();
  },
  methods: {
    // 识别按钮
    recognize() {
      this.fileList = [];
      this.audioDialogFormVisible = true;
    },

    // 识别音频
    async recognizeAudio() {
      console.log("recognizeAudio");
      console.log("file length: " + this.fileList.length);
      this.isRecognizing = true; // 开始识别，设置加载状态
      let formData = new FormData();
      formData.append(`audio_file1`, this.fileList[0].raw);
      // this.fileList.forEach((file, index) => {
      //   formData.append(`audio_file${index + 1}`, file.raw);
      // });
      axios
          .post(`${this.httpTarget}/recognize`, formData)
          .then((response) => {
            if (response.data.result === "Success") {
              console.log(response)
              this.info = `识别的指令为：${response.data.data.possible_action}
                识别的用户为：${response.data.data.username}(${response.data.data.user_id})`;
            } else if (response.data.result === "Failed" && response.data.error !== undefined) {
              this.$message.error(
                  `识别失败：未找到足够相似度的对象`
              );
              this.info = `识别失败：未找到足够相似度的对象,最大相似度为 ${response.data.data.similarity_score}`
            } else {
              this.$message.error(`发生错误: ${response.data.data.error}`);
            }
            this.audioDialogFormVisible = false;
            this.fileList = [];
          })
          .catch((error) => {
            this.$message.error(`识别失败: ${error.message}`);
          })
          .finally(() => {
            this.isRecognizing = false; // 识别结束，取消加载状态
          });
    },

    // 添加用户
    addUser() {
      this.dialogTitle = "新增用户";
      this.isEditing = false;
      this.userFormData = {
        username: "",
        permission_level: 1,
      };
      this.fileList = [];
      this.userDialogFormVisible = true;
    },

    // 编辑用户
    editUser(index, row) {
      this.dialogTitle = "修改用户";
      this.isEditing = true;
      this.userFormData = {
        username: row.username,
        permission_level: row.permission_level,
        user_id: row.id,
      };
      this.userDialogFormVisible = true;
    },

    // 在上传文件之前检查文件格式
    handleBeforeUpload(file) {
      const isWav = file.type === "audio/wav";
      if (!isWav) {
        this.$message.error("只能上传wav格式的文件");
      }
      return isWav;
    },

    // 处理文件上传
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },

    // 提交表单
    async submitForm() {
      this.isUploading = true;
      if (
          !this.userFormData.username ||
          !this.userFormData.permission_level ||
          (!this.isEditing && this.fileList.length === 0)
      ) {
        this.isUploading = false;
        this.$message.error(
            "请填写完整信息，包括用户名、等级和至少一个音频文件"
        );
        return;
      }

      const formData = new FormData();
      formData.append("username", this.userFormData.username);
      formData.append("permission_level", this.userFormData.permission_level);
      if (this.isEditing) {
        formData.append("id", this.userFormData.user_id);
      }
      this.fileList.forEach((file, index) => {
        formData.append(`audio_file${index + 1}`, file.raw);
      });

      try {
        if (this.isEditing) {
          console.log(
              this.userFormData.username +
              " " +
              this.userFormData.permission_level +
              " " +
              this.userFormData.user_id
          );
          axios
              .post(`${this.httpTarget}/update_user`, formData)
              .then((response) => {
                if (response.data.result === "Success") {
                  this.$message.success(`用户修改成功`);
                  this.getUser();
                } else {
                  this.$message.error(`修改失败: ${response.data.result}`);
                }
              })
              .catch((error) => {
                this.$message.error(`修改失败: ${error.message}`);
              })
              .finally(() => {
                this.isUploading = false;
              });
        } else {
          axios
              .put(`${this.httpTarget}/load`, formData)
              .then((response) => {
                if (response.data.result === "Success") {
                  this.$message.success(`用户新增成功`);
                  this.getUser();
                } else {
                  this.$message.error(`新增失败: ${response.data.data.error}`);
                }
              })
              .catch((error) => {
                this.$message.error(`新增失败: ${error.message}`);
              })
              .finally(() => {
                this.isUploading = false;
              });
        }
        // const url = this.isEditing
        //   ? `${this.httpTarget}/update_user`
        //   : `${this.httpTarget}/load`;
        // const response = await axios.put(url, formData, {
        //   headers: {
        //     "Content-Type": "multipart/form-data",
        //   },
        // });

        this.userDialogFormVisible = false;
        this.fileList = [];
        this.userFormData = {
          username: "",
          permission_level: 1,
        };
        this.getUser();
      } catch (error) {
        console.error("提交表单出错:", error);
      }
    },

    // 获取用户数据
    getUser() {
      this.isUsersLoading = true
      axios.get(`${this.httpTarget}/get_all_user`).then((response) => {
        if (response.data.result === "Success") {
          const users = response.data.data.user_set.map((user) => ({
            username: user.username,
            permission_level: user.permission_level,
            id: user.id,
          }));
          this.totalUsers = users.length;
          this.userList = users.slice(
              (this.currentPageUser - 1) * this.pageSizeUser,
              this.currentPageUser * this.pageSizeUser
          );
        } else {
          this.$message.error(`获取用户列表失败: ${response.data.data.error}`);
        }
      }).catch((error) => {
        this.$message.error(`请求用户列表失败: ${error.message}`);
      })
          .finally(() => {
            this.isUsersLoading = false;
          });
    },

    // 删除确认
    confirmDeleteUser(row) {
      this.$confirm(
          `确定要删除用户 "${row.username}(id=${row.id})" 吗?`,
          "确认删除",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }
      )
          .then(() => {
            // 调用删除函数
            this.deleteUser(row);
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
    },

    // 删除指令
    deleteUser(row) {
      let formData = new FormData();
      formData.append("user_id", row.id);
      axios
          .post(`${this.httpTarget}/delete_user`, formData)
          .then((response) => {
            if (response.data.result === "Success") {
              this.$message.success(`用户 "${row.username}" 删除成功`);
              this.getUser();
            } else {
              this.$message.error(`删除失败: ${response.data.data.error}`);
            }
          })
          .catch((error) => {
            this.$message.error(`删除失败: ${error.message}`);
          });
    },

    userAllClear() {
      this.isUploading = true
      axios
          .get(`${this.httpTarget}/delete_all_user`,)
          .then((response) => {
            if (response.data.result === "Success") {
              this.$message.success("执行成功")
            } else if (response.data.result === "Failed") {
              this.$message.error("执行失败")
            } else {
              this.$message.error("执行错误")
            }
          })
          .catch((e) => {
            this.$message.error(`执行错误${e.message}`);
          })
          .finally(() => {
            this.getUser()
            this.isUploading = false;
          })
    },
    // 添加指令
    addCommand() {
      this.$prompt("请输入新的指令", "新增指令", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /.*/,
        inputErrorMessage: "请输入指令",
      })
          .then(({value}) => {
            if (value.trim() === "") {
              this.$message.error("指令不能为空");
            } else {
              let formData = new FormData();
              formData.append("action", value.trim());
              axios
                  .post(`${this.httpTarget}/add_action`, formData)
                  .then((response) => {
                    if (response.data.result === "Success") {
                      this.$message.success(
                          `指令添加成功: ${response.data.result}`
                      );
                      this.getCommand();
                    } else {
                      this.$message.error(`指令添加失败: ${response.data.data.error}`);
                    }
                  })
                  .catch((error) => {
                    this.$message.error(`指令添加失败: ${error.message}`);
                  });
            }
          })
          .catch(() => {
            this.info = "已取消添加指令";
          });
    },

    // 删除确认
    confirmDeleteCommand(row) {
      this.$confirm(`确定要删除指令 "${row.command}" 吗?`, "确认删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            // 调用删除函数
            this.deleteCommand(row);
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
    },

    // 删除指令
    deleteCommand(row) {
      let formData = new FormData();
      formData.append("action", row.command);
      axios
          .post(`${this.httpTarget}/delete_action`, formData)
          .then((response) => {
            if (response.data.result === "Success") {
              this.$message.success(`指令 "${row.command}" 删除成功`);
              this.getCommand();
            } else {
              this.$message.error(`删除失败: ${response.data.data.error}`);
            }
          })
          .catch((error) => {
            this.$message.error(`删除失败: ${error.message}`);
          });
    },

    // 获取指令数据
    getCommand() {
      this.isCommandLoading = true
      axios.get(`${this.httpTarget}/get_all_action`).then((response) => {
        if (response.data.result === "Success") {
          const commands = response.data.data.action_set.map((action) => ({
            command: action,
          }));
          this.totalCommands = commands.length;
          this.commandList = commands.slice(
              (this.currentPageCommand - 1) * this.pageSizeCommand,
              this.currentPageCommand * this.pageSizeCommand
          );
        } else {
          this.$message.error(`获取指令列表失败: ${response.data.data.error}`);
        }
      }).catch((error) => {
        this.$message.error(`请求指令列表失败: ${error.message}`);
      })
          .finally(() => {
            this.isCommandLoading = false;
          });
    },

    // 分页大小改变时的处理（用户表格）
    handleSizeChangeUser(size) {
      this.pageSizeUser = size;
      this.getUser();
    },

    // 分页大小改变时的处理（指令表格）
    handleSizeChangeCommand(size) {
      this.pageSizeCommand = size;
      this.getCommand();
    },

    // 当前页码改变时的处理（用户表格）
    handleCurrentChangeUser(page) {
      this.currentPageUser = page;
      this.getUser();
    },

    // 当前页码改变时的处理（指令表格）
    handleCurrentChangeCommand(page) {
      this.currentPageCommand = page;
      this.getCommand();
    },
  },
};
</script>
